package com.punai.file.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punai.common.exception.ServiceException;
import com.punai.common.properties.FileUpPathConfig;
import com.punai.common.properties.SqliteUpPathConfig;
import com.punai.file.domain.FileUploadFile;
import com.punai.file.mapper.FileUploadFileMapper;
import com.punai.file.service.UploadFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class FileUploadFileServiceImpl extends ServiceImpl<FileUploadFileMapper, FileUploadFile> implements UploadFileService {

    @Autowired
    private FileUploadFileMapper uploadFileMapper;

    @Autowired
    private FileUpPathConfig fileUpPathConfig;

    @Override
    public String disposeFile(MultipartFile file,Long companyId) {
        String basePath = fileUpPathConfig.getBasePath();
        FileUploadFile fileupload = new FileUploadFile();
        String name = file.getOriginalFilename();
        fileupload.setFileName(name);
        // 文件后缀名
        String suffix = FileUtil.getSuffix(name);
        String reName = IdUtil.fastUUID();
        String allReName = reName + (StrUtil.isEmpty(suffix) ? "" : "." + suffix);
        File saveFile = new File(basePath, allReName);
        try{
            // 将文件存放在目录下
            FileUtil.writeFromStream(file.getInputStream(),saveFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("上传失败");
        }
        fileupload.setFileSize(FileUtil.readableFileSize(saveFile));
        fileupload.setFilePath(allReName);
        fileupload.setCompanyId(companyId);
        uploadFileMapper.insert(fileupload);
        return fileupload.getId();
    }

    @Override
    public int delFile(String id, Long companyId) {
        FileUploadFile uploadFile = uploadFileMapper.selectById(id);
        String filePath = uploadFile.getFilePath();
        String path = SqliteUpPathConfig.getCuspath();
        FileUtil.del(new File(path,filePath));
        return uploadFileMapper.deleteById(id);
    }

}
